<?php 
namespace app\index\wechat;

class Wechat{

	//验证消息
	function valid(){
		if($this->chkSignature()){
			echo input('get.echostr');
		}else{
			echo 'error';
			exit;
		}
	}
	

	//验证签名
	function chkSignature(){
		//加密签名
		$signature=input('get.signature');
		//时间戳
		$timestamp=input('get.timestamp');
		//随机数
		$nonce=input('get.nonce');
		//随机字符串
		$echostr=input('get.echostr');
		//token
		$token=config('token');

		//字典序排序
		$tmpArr=array($token,$timestamp,$nonce);
		sort($tmpArr,SORT_STRING);
		//拼接字符串，进行sha1加密
		$tmpStr=implode($tmpArr);
		$tmpStr=sha1($tmpStr);

		//加密签名的比较
		if($tmpStr==$signature){
			return true;
		}else{
			return false;
		}
	}

	// 接收消息
	function receiveMsg(){
		// 获取原生的post过来的数据
		$postStr=$GLOBALS['HTTP_RAW_POST_DATA'];
		if(!$postStr){
			echo 'erro';
			exit;
		}else{
			// 得到的xml原生数据变成php对象
			$o=simplexml_load_string($postStr);
			$this->chkMsgType($o);
		}
	}

	// 判断接收消息的类型
	/**
	 * @param o string
	 * @return xml
	 */
	function chkMsgType($o){
		switch ($o->MsgType) {
			//接收到文本消息
			case 'text':
				// 调用机器人接口进行回复
				// $url='http://op.juhe.cn/robot/index?info='.$o->Content.'&key='.config('jhAppkey');
				// $res=curl($url);
				// $this->replyText($o,$res['result']['text']);

				// $arr=[
				// 	[
				// 		"Title"=>'JavaScriptAPI设计原则',
				// 		"Description"=>'api design',
				// 		"PicUrl"=>'http://www.jzcoder.com/wp-content/uploads/LubImg/20160329213238463310.jpg',
				// 		"Url"=>'http://www.jzcoder.com/php/1515.html'
				// 	],
				// 	[
				// 		"Title"=>'方便境外自驾',
				// 		"Description"=>'travel by yourself',
				// 		"PicUrl"=>'http://p.xincheping.com/201702/49/dim600x400_74ada9d7d449f0b841d8e5afb36ce1_700nomk.jpg',
				// 		"Url"=>'http://www.xincheping.com/news/103485.html'
				// 	]
				// ];
				// $this->replyArticle($o,$arr);

			    
				break;
			//接收到图片消息
			case 'image':
				$this->replyImage($o,$o->MediaId);
				break;
			//接收到语音消息
			case 'voice':
				$this->replyVoice($o,$o->MediaId);
				break;
			case 'location':
				$this->replyText($o,$o->Location_X.','.$o->Location_Y);
				break;
			// 接收到视频消息
			case 'video':
				$arr=[
					'ToUserName'=>$o->FromUserName,
					'FromUserName'=>$o->ToUserName,
					'CreateTime'=>time(),
					'MediaId'=>$o->MediaId,
					'Title'=>'这是回复的视频',
					'Description'=>'这是回复的视频描述',
				];
				$this->replyVideo($o,$arr);
				break;
			case 'event':
				$this->receiveEvent($o);
				break;
			default:
				# code...
				break;
		}
	}

	//接收到事件的推送
	function receiveEvent($o){
		switch ($o->Event) {
			case 'subscribe':
				# code...
				$this->replyText($o,'欢迎关注我们的公众号');
				break;
			case 'SCAN':
				# code...
				break;
			case 'LOCATION':

				$this->replyText($o,$o->Latitude);

				break;
			case 'CLICK':

				break;
			case 'VIEW':

				break;
			
			default:
				# code...
				$this->replyText($o,$o->Latitude);

				break;
		}
	}

	function sendTemplate($o,$tid){
		$url='https://api.weixin.qq.com/cgi-bin/message/template/send?access_token='.$this->getAccessToken();
		// {
  //          "touser":"OPENID",
  //          "template_id":"ngqIpbwh8bUfcSsECmogfXcV14J0tQlEpBO27izEYtY",
  //          "url":"http://weixin.qq.com/download",            
  //          "data":{
  //                  "first": {
  //                      "value":"恭喜你购买成功！",
  //                      "color":"#173177"
  //                  },
  //          }
  //      }
		$data=[
			"touser"=>$o->FromUserName,
			'template_id'=>$tid,
			"url"=>"http://jzcoder.com",
			"data"=>[
				"a"=>[
					"value"=>'500',
					'color'=>"#00ff00"
				],
				"b"=>[
					"value"=>'焦作',
					'color'=>"#ff0000"
				]
			]
		];

		$res=curl($url,json_encode($data));
		return $res;
	}

	function replyArticle($o,$arr){
		$xml='<xml>
				<ToUserName><![CDATA[%s]]></ToUserName>
				<FromUserName><![CDATA[%s]]></FromUserName>
				<CreateTime>%d</CreateTime>
				<MsgType><![CDATA[news]]></MsgType>
				<ArticleCount>%d</ArticleCount>
				<Articles>';
		$xml=sprintf($xml,$o->FromUserName,$o->ToUserName,time(),count($arr));
		for($i=0;$i<count($arr);$i++){
			$xml.='<item>
				<Title><![CDATA['.$arr[$i]['Title'].']]></Title> 
				<Description><![CDATA['.$arr[$i]['Description'].']]></Description>
				<PicUrl><![CDATA['.$arr[$i]['PicUrl'].']]></PicUrl>
				<Url><![CDATA['.$arr[$i]['Url'].']]></Url>
				</item>';
		}
		$xml.='</Articles>
				</xml> ';
		echo $xml; 

	}

	// 回复视频消息
	function replyVideo($o,$arr=null){
		$xml='<xml>
			<ToUserName><![CDATA[%s]]></ToUserName>
			<FromUserName><![CDATA[%s]]></FromUserName>
			<CreateTime>%d</CreateTime>
			<MsgType><![CDATA[video]]></MsgType>
			<Video>
			<MediaId><![CDATA[%s]]></MediaId>
			<Title><![CDATA[%s]]></Title>
			<Description><![CDATA[%s]]></Description>
			</Video> 
			</xml>';
		echo sprintf($xml,$arr['ToUserName'],$arr['FromUserName'],$arr['CreateTime'],$arr['MediaId'],$arr['Title'],$arr['Description']);
	}

	// 回复文本消息
	function replyText($o,$content=''){
		$xml='<xml>
			<ToUserName><![CDATA[%s]]></ToUserName>
			<FromUserName><![CDATA[%s]]></FromUserName>
			<CreateTime>%d</CreateTime>
			<MsgType><![CDATA[text]]></MsgType>
			<Content><![CDATA[%s]]></Content>
			</xml>';
		echo sprintf($xml,$o->FromUserName,$o->ToUserName,time(),$content);
	}

	// 回复图片消息
	function replyImage($o,$mediaid=''){
		$xml='<xml>
			<ToUserName><![CDATA[%s]]></ToUserName>
			<FromUserName><![CDATA[%s]]></FromUserName>
			<CreateTime>%d</CreateTime>
			<MsgType><![CDATA[image]]></MsgType>
			<Image>
			<MediaId><![CDATA[%s]]></MediaId>
			</Image>
			</xml>';
		echo sprintf($xml,$o->FromUserName,$o->ToUserName,time(),$mediaid);
	}

	// 回复语音消息
	function replyVoice($o,$mediaid=''){
		$xml='<xml>
			<ToUserName><![CDATA[%s]]></ToUserName>
			<FromUserName><![CDATA[%s]]></FromUserName>
			<CreateTime>%d</CreateTime>
			<MsgType><![CDATA[voice]]></MsgType>
			<Voice>
			<MediaId><![CDATA[%s]]></MediaId>
			</Voice>
			</xml>';
		echo sprintf($xml,$o->FromUserName,$o->ToUserName,time(),$mediaid);
	}

	function sendGroup(){
		$url='https://api.weixin.qq.com/cgi-bin/message/mass/sendall?access_token='.$this->getAccessToken();

		$postArr=[
			"filter"=>[
				"is_to_all"=>true
			],
			"text"=>[
				"content"=>urlencode('你好')
			],
			"msgtype"=>"text"
		];
		$post=json_encode($postArr);
		$res=curl($url,$post);
		return $res;
	}

	function getAccessToken(){
		if(cache('access_token')){
			return cache('access_token');
		}else{
			// access_token地址
	    	$url='https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.config('appID').'&secret='.config('appsecret');
	    	$res=curl($url);
	    	cache('access_token',$res['access_token'],7100);
	    	return $res['access_token'];
		}
	}


	// 获取网页的access_token
	function getWebAccessToken($code){
		if(cache('web_access_token')){
			return cache('web_access_token');
		}else{
			$url='https://api.weixin.qq.com/sns/oauth2/access_token?appid='.config('appID').'&secret='.config('appsecret').'&code='.$code.'&grant_type=authorization_code';
			$res=curl($url);
			cache('web_access_token',$res,7100);
			return $res;
		}
		
	}

	//通过网页的access_token获得用户信息
	function getUserInfo($ac){
		$urlInfo='https://api.weixin.qq.com/sns/userinfo?access_token='.$ac['access_token'].'&openid='.$ac['openid'].'&lang=zh_CN';
		
        $userinfo=curl($urlInfo);
        return $userinfo;
	}




}